package com.bawei.park2302.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.utils.utils.mvi.BaseActivity
import com.bawei.lib_base.utils.utils.mvi.UiState
import com.bawei.park2302.R
import com.bawei.park2302.databinding.ActivityRegisterBinding
import com.blankj.utilcode.util.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.random.Random

@Route(path = "/app/RegisterActivity")
@AndroidEntryPoint
class RegisterActivity : BaseActivity<ActivityRegisterBinding,UserIntent,UserViewModel>() {
    override val binding: ActivityRegisterBinding by lazy {
        ActivityRegisterBinding.inflate(layoutInflater)
    }
    override val vm: UserViewModel by viewModels<UserViewModel>()

    lateinit var timer : Timer
    var time = 6

    override fun initView() {
        binding.registerGetCode.setOnClickListener {
            val random = Random.nextInt(100000, 999999).toString()
            binding.registerCode.setText(random)
            timer = Timer()
            lifecycleScope.launch(Dispatchers.IO){
                timer.schedule(object : TimerTask(){
                    override fun run() {
                        time--
                        lifecycleScope.launch {
                            binding.registerGetCode.text = "${time}S后获取验证码"
                        }
                        if (time == 0){
                            time = 6
                            timer.cancel()
                            lifecycleScope.launch {
                                binding.registerGetCode.text = "重新获取验证码"
                            }
                        }
                    }
                },0,1000)
            }
        }

        binding.btnRegister.setOnClickListener {
            val username = binding.registerUsername.text.toString()
            val password = binding.registerPassword.text.toString()

            vm.sendIntent(UserIntent.register(username,password))
        }
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ARouter.getInstance().build("/app/LoginActivity")
                            .withString("username",binding.registerUsername.text.toString())
                            .withString("password",binding.registerPassword.text.toString())
                            .navigation()
                    }

                    is UiState.onError ->{
                        Log.d("===",it.msg)
                    }

                    else -> {}
                }
            }
        }
    }
}